var purl="/wcsi/img/nopicture.png";
$(function() {

	initPageInfo();

	$("#submitBtn").click(function() {
		saveOrUpdateInspectInfo();

	});

});
$("#locationimg").click(function(ev){  
	GetYourLocation();
});
$(document).ready(function() {
	GetYourLocation();
	$(".ui-btn-icon-right").removeClass("ui-btn-icon-right");
});
$("body").on("click",".gotomap",function() {
	$("#mapLocationDes").html($(this).parent().next().html());
});
function GetYourLocation(){
	$("#locationDes").html("正在获取位置......");  
    //创建百度地图控件  
    var geolocation = new BMap.Geolocation();  
    geolocation.getCurrentPosition(function(r){  
        if(this.getStatus() == BMAP_STATUS_SUCCESS){  
            //以指定的经度与纬度创建一个坐标点  
            var pt = new BMap.Point(r.point.lng,r.point.lat);
            $("#lng").val(r.point.lng);
            $("#lat").val(r.point.lat);
            //创建一个地理位置解析器  
            
            var geoc = new BMap.Geocoder();  
            geoc.getLocation(pt, function(rs){//解析格式：城市，区县，街道  
            		var addComp = rs.addressComponents;  
            		$("#locationDes").html(addComp.city + ", " + addComp.district + ", " + addComp.street+", "+ addComp.streetNumber);  
            });
            
            var data = {
    				"longitude" : $("#lng").val(),
    				"latitude" : $("#lat").val(),
    				"id" : "exdePoint"
    			}
    			createFlickerPoint(data, 'html');
    			setTimeout(function() {
    				setCenter();
    			}, 500);
        }  
        else {  
            $("#locationDes").html('定位失败');  
        }          
    },{enableHighAccuracy: true})//指示浏览器获取高精度的位置，默认false  
};

$("#goHome").click(
		function() {

			$("#goHome").attr(
					"href",
					rootPath + "/ui/bussinessmain?device=mobile&&identify="
							+ $("#identify").val());
		});
$('#fileclick').on('click', function() {
	return $("#file_upload").click();
});
$("#file_upload")
		.change(
				function() {
					var $file = $(this);
					var fileObj = $file[0];
					var windowURL = window.URL || window.webkitURL;
					var dataURL;
					var $img = $("#avatart");

					if (fileObj && fileObj.files && fileObj.files[0]) {
						dataURL = windowURL.createObjectURL(fileObj.files[0]);
						$img.attr('src', dataURL);
					} else {
						dataURL = $file.val();
						var imgObj = document.getElementById("preview");
						// 两个坑:
						// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
						// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
						imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
						imgObj.filters
								.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

					}
				});
function initPageInfo() {
	$.ajax({
		url : window.rootPath + "/ui/bussinessInspection/findOptsByGroup",
		dataType : 'JSON',
		type : 'get',
		success : function(result) {

			if (result.code == 1) {

				var environment = result.data.environment;
				var cityOrder = result.data.cityOrder;
				var greenCondition = result.data.greenCondition;
				var noneOpt = result.data.noneOpt;

				var contenthtml = '<optgroup label="其他问题">';
				for (var i = 0; i < noneOpt.length; i++) {
					contenthtml += '<option value="'
							+ noneOpt[i].id + '">' + noneOpt[i].title
							+ '</option>';

				}

				contenthtml += '<optgroup label="环境卫生">';
				for (var i = 0; i < environment.length; i++) {
					contenthtml += '<option value="' + environment[i].id + '">'
							+ environment[i].title + '</option>';

				}
				contenthtml += "</optgroup>";
				// alert(contenthtml);
				$("#myselect").append(contenthtml);
				$("#myselect").selectmenu("refresh", true);

				contenthtml = '<optgroup label="市容秩序">';
				for (var i = 0; i < cityOrder.length; i++) {
					contenthtml += '<option value="' + cityOrder[i].id + '">'
							+ cityOrder[i].title + '</option>';
				}
				contenthtml += "</optgroup>";
				$("#myselect").append(contenthtml);
				$("#myselect").selectmenu("refresh", true);

				contenthtml = '<optgroup label="绿化美化">';
				for (var i = 0; i < greenCondition.length; i++) {
					contenthtml += '<option value="' + greenCondition[i].id
							+ '">' + greenCondition[i].title + '</option>';
				}
				contenthtml += "</optgroup>";
				$("#myselect").append(contenthtml);
				$("#myselect").selectmenu("refresh", true);

			}
		}
	});
};

var oldlist=[];

$('#myselect').change(function(){  
	var list= $(this).val();
	if(oldlist==null){
		oldlist=[];
	}
	if(list==null){
	
		for(var i=0;i<oldlist.length;i++){
			$("#"+oldlist[i]+"_li").remove();
			$("#file_"+oldlist[i]).remove();
		}
		$('#inspectProb').listview('refresh');
		oldlist=list;
	}else{
		for(var i=0;i<list.length;i++){
			var isOk=false;
			for(var j=0;j<oldlist.length;j++){
				if(list[i]==oldlist[j]){
				oldlist.splice(j,1);
				isOk=true;
				break;
				}
			}
			if(!isOk){
				var  contenthtml ='<li id="'+list[i]+'_li">'+'<a id="'+list[i]+'" href="#sPanel" data-transition="slide" class="aclick">'
					+'<div class="listViewImg-self">'
					+'<img src="'+purl+'" id="'+list[i]+'_avatartD"/>'
					+'</div>'
					+'<div class="listViewContent-self">'
					+'<p class="listViewTitle-self">' + $('#myselect option[value="'+list[i]+'"]').text() + '</p>'
					+'<p class="listViewMemo-self" id="'+list[i]+'_remarkD"></p>'
					+'</div>'
					+ '</a>'
					+ '</li>';  
			  $("#inspectProb").append(contenthtml);
			  $("#mainContent").append('<input type="file" class="fileClick" id="file_'+list[i]+'" name="'+list[i]+'" style="display: none;"/>');
			}
		}
		for(var i=0;i<oldlist.length;i++){
			$("#"+oldlist[i]+"_li").remove();
			$("#file_"+oldlist[i]).remove();
		}
		oldlist=list;
		$('#inspectProb').listview('refresh');
		$(".ui-btn-icon-right").removeClass("ui-btn-icon-right");
	}
});
$("body").on("click", ".aclick", function (){
	var a=$(this).attr("id");
	$("#currentId").val(a);
	$("#remarkD").val($("#"+a+"_remarkD").html());
	
	if($("#"+a+"_avatartD").attr("src")!=purl){
		$("#avatartD").attr("src",$("#"+a+"_avatartD").attr("src"));
	}else{
		$("#avatartD").attr("src",'/wcsi/img/upload.png');
	}
});
$('#saveBtnT').on('click', function () {
	var a=$("#currentId").val();
	
	$("#"+a+"_remarkD").html($("#remarkD").val());
	
	
	var imgurl=$("#avatartD").attr("src");
	
	if(imgurl!="/wcsi/img/upload.png")
	$("#"+a+"_avatartD").attr("src",imgurl);
	
});

$('#detailfileclick').on('click', function () {
	var a=$("#currentId").val();
	return  $("#file_"+a).click();
});
$("body").on("change", ".fileClick", function (){
	var $file = $(this);
    var fileObj = $file[0];
    var windowURL = window.URL || window.webkitURL;
    var dataURL;
    var $img = $("#avatartD");

    if (fileObj && fileObj.files && fileObj.files[0]) {
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        $img.attr('src', dataURL);
    } else {
        dataURL = $file.val();
        var imgObj = document.getElementById("preview");
        // 两个坑:
        // 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
        // 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

    }
	});
function saveOrUpdateInspectInfo() {
	
var businessInspectDetail=new Array();
	
	for(var i=0;i<oldlist.length;i++){
		var temp ={
				"picAddr1":$("#"+oldlist[i]+"_avatartD").attr('src'),
				"remark":$("#"+oldlist[i]+"_remarkD").html(),
				"inspectOpt":{
					"id":oldlist[i]
				}
			};
		businessInspectDetail.push(temp);
		}
	
	var data={};

	/*var bussinessId = $("#identify").val();
	var optionId = $("#optionId").val();
	// var needCheck = $("#needCheck").val();
	var remark = $("#remark").val();

	var enviromentIds = $("#myselect").val();

	if (enviromentIds == '' || enviromentIds == null
			|| enviromentIds == undefined) {
		alert('请选择巡检选项!');
		return false;
	}

	var param = {
		"bussinessId" : bussinessId,
		"optionId" : optionId,//良好 及格
		// "needCheck" : needCheck,
		"remark" : remark,
		"enviromentIds" : enviromentIds
	};

	$.ajaxFileUpload({
		url : window.rootPath + "/ui/bussinessInspection/saveOrUpdate",
		secureuri : false,// 是否需要安全协议
		fileElementId : 'file_upload',// 文件上传的Id属性
		dataType : 'JSON',
		data : param,
		success : function(result, status) {
			window.location.href = window.rootPath
					+ "/ui/bussinessInspection?device=mobile&identify="
					+ bussinessId;
		}
	});*/
	
	var lng=0;
	 if($("#lng").val()!=undefined&&$("#lng").val()!=""){
		 lng=$("#lng").val();
	 }
    var lat=0;
    if($("#lat").val()!=undefined&&$("#lat").val()!=""){
   	 lat=$("#lat").val();
	 }
	
	var bussinessInspection={
			"longitude":lng,
			"latitude":lat,
			//"checkCondition":$("#checkCondition").val(),
			'inspectCondition':{
				"id": $("#optionId").val()
			},
			
			"remark":$("#remark").val(),
			"pictureAddr":''/*$("#pictureAddr").attr(''src)*/
	};	
	var fileIds = new Array();
	var fileNames="";
	    var formHandle = document.getElementById("mainContent");
	    var tagElements = formHandle.getElementsByTagName('input');
	    for (var j = 0; j < tagElements.length; j++) {
	        element = tagElements[j];
	        if ("file" == element.type) {
	            fileIds.push(element.id);
	            fileNames+=element.name+";";
	        }
	    }
		data={
				"bussinessId":$("#identify").val(),
				//"inspectionIdList":$("#inspectionIdList").val(),
				"bussinessInspection":JSON.stringify(bussinessInspection),
				"businessInspectDetail":JSON.stringify(businessInspectDetail),
				"fileNames":fileNames
		};
		
		$.ajaxFileUpload({
			url : window.rootPath + "/ui/bussinessInspection/saveOrUpdate",
			secureuri : false,// 是否需要安全协议
			fileElementId : fileIds,// 文件上传的Id属性
			dataType : 'text',
			data : data,
			success : function(result, status) {
				window.location.href = window.rootPath
				+ "/ui/bussinessInspection?device=mobile&identify="
				+ $("#identify").val();
			}
		});
		
	$("#popupView").popup("open");
	// 设置按钮无法点击
	// $("#submitBtn").prop("disabled", true);
	return false;
};